import hashlib
import traceback
from django.conf import settings
from django.contrib.auth.models import User
import vkontakte
from apps.users.models import UserProfile

class VKServiceException(Exception):
    pass

class VKService(object):

    TYPE_VK = UserProfile.TYPE_VK
    TYPE_VK_APPLICATION = UserProfile.TYPE_VK_APPLICATION

    TYPES = [TYPE_VK, TYPE_VK_APPLICATION]

    def get_api_instance(self, type):
        if not type in self.TYPES:
            raise VKServiceException("Undefined type")

        if type == self.TYPE_VK:
            return vkontakte.API(settings.VK_API_ID, settings.VK_API_SECRET)
        if type == self.TYPE_VK_APPLICATION:
            return vkontakte.API(settings.VK_APPLICATION_API_ID, settings.VK_APPLICATION_API_SECRET)

    def get_auth_key(self, type, user_id):
        if not type in self.TYPES:
            raise VKServiceException("Undefined type")

        auth_key_src = ""

        if type == self.TYPE_VK:
            auth_key_src = "%s_%s_%s" % (
                settings.VK_API_ID,
                user_id,
                settings.VK_API_SECRET
            )
        if type == self.TYPE_VK_APPLICATION:
            auth_key_src = "%s_%s_%s" % (
                settings.VK_APPLICATION_API_ID,
                user_id,
                settings.VK_APPLICATION_API_SECRET
            )

        return hashlib.md5(auth_key_src).hexdigest()


    def post_to_wall(self, type, user_id, message):
        api = self.get_api_instance(type)

        vk_user_data = api.get(
            "wall.post",
            owner_id=user_id,
            message=message
        )[0]
        return vk_user_data


    def get_user(self, type, user_id, access_token):
        if not type in self.TYPES:
            raise VKServiceException("Undefined type")

        api = self.get_api_instance(type)
        auth_key = self.get_auth_key(type, user_id)

        vk_user_data = api.get(
            "users.get",
            uid=user_id,
            #access_token=access_token,
            fields="uid, first_name, last_name, nickname, screen_name, photo, photo_medium, photo_big"
        )[0]

        user = None

        try:
            user = User.objects.get(
                email = "%s@vk.com" % user_id
            )

        except User.DoesNotExist:
            username = vk_user_data.get("nickname", vk_user_data.get("screen_name", "vk%s" % user_id))
            if User.objects.filter(username = username).count():
                username = vk_user_data.get("screen_name", "vk%s" % user_id)
                if User.objects.filter(username = username).count():
                    username = "%s%s" % (username, user_id)

            if len(username) < 2:
                username = "vk%s" % user_id

            user = User.objects.create(
                username = username,
                email = "%s@vk.com" % user_id,
                first_name = vk_user_data.get("first_name", ""),
                last_name = vk_user_data.get("last_name", "")
            )
            user.set_password(auth_key)
            user.save()

            UserProfile.objects.create(
                user = user,
                type = type,
                avatar = vk_user_data.get("photo", ""),
                vk_user_id = user_id
            )

        return user

